from app.models.settings import Settings, SettingsUpdate
from app.database.database import get_db_with_dict_factory
import json

class SettingsService:
    def __init__(self):
        self.db = get_db_with_dict_factory()
        
    async def get_settings(self) -> dict:
        """获取系统设置"""
        cursor = self.db.cursor()
        cursor.execute("SELECT * FROM settings WHERE id = 1")
        settings = cursor.fetchone()
        
        if not settings:
            # 如果没有设置，创建默认设置
            default_settings = {
                "siteName": "智能写作平台",
                "defaultLanguage": "zh-CN",
                "defaultAIModel": None
            }
            
            cursor.execute(
                "INSERT INTO settings (id, data) VALUES (1, ?)",
                (json.dumps(default_settings),)
            )
            self.db.commit()
            
            return default_settings
        
        return json.loads(settings['data'])
        
    async def update_settings(self, settings: SettingsUpdate) -> dict:
        """更新系统设置"""
        cursor = self.db.cursor()
        
        # 检查设置是否存在
        cursor.execute("SELECT * FROM settings WHERE id = 1")
        existing = cursor.fetchone()
        
        settings_data = settings.dict()
        
        if existing:
            cursor.execute(
                "UPDATE settings SET data = ? WHERE id = 1",
                (json.dumps(settings_data),)
            )
        else:
            cursor.execute(
                "INSERT INTO settings (id, data) VALUES (1, ?)",
                (json.dumps(settings_data),)
            )
            
        self.db.commit()
        return settings_data
        
    def __del__(self):
        """确保数据库连接被正确关闭"""
        if hasattr(self, 'db'):
            self.db.close() 